//
//  MySoundMoodViewController.m
//  SunXi
//
//  Created by dllo on 15/12/3.
//  Copyright © 2015年 大远. All rights reserved.
//

#import "MySoundMoodViewController.h"

@interface MySoundMoodViewController ()<AVAudioRecorderDelegate>

@end

@implementation MySoundMoodViewController
{
    UILabel* timeLabel;
    
    NSTimer* timer;
    float recordTime;
    int playTime;
    int playDuration;
    int second;
    int minute;
    int hour;
    
    UIButton *playButton;
    UIButton *pauseButton;
    UILabel* playLabel;
    UILabel* pauseLabel;
    
    AVAudioRecorder *audioRecorder;
    AVAudioPlayer *audioPlayer;
    AVAudioSession * audioSession;
    
    NSURL* recordUrl;
    NSURL* mp3FilePath;
    NSURL* audioFileSavePath;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    UIImageView *imageview = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"drawBackPic.jpg"]];
    [SV addSubview:imageview];
    [imageview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(SV).with.insets(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    
    [self initializeUI];
}

- (void)initializeUI {
    
    playButton = [[UIButton alloc] initWithFrame:CGRectMake(PLAYBUTTON_X, PLAYBUTTON_Y, PLAYBUTTON_WIDTH, PLAYBUTTON_HEIGHT)];
    [playButton setImage:[UIImage imageNamed:@"play_button.png"] forState:UIControlStateNormal];
    playButton.tag = NEW_PLAY_BUTTON_TAG;
    [playButton addTarget:self action:@selector(clickOnButton:) forControlEvents:UIControlEventTouchUpInside];
    
    playLabel = [[UILabel alloc] initWithFrame:CGRectMake(PLAYBUTTON_X, PLAYBUTTON_Y+PLAYBUTTON_HEIGHT, PLAYBUTTON_WIDTH, NAVBAR_HEIGHT)];
    [playLabel setText:@"播放"];
    [playLabel setTextAlignment:NSTextAlignmentCenter];
    
    pauseButton = [[UIButton alloc] initWithFrame:CGRectMake(PLAYBUTTON_X, PLAYBUTTON_Y, PLAYBUTTON_WIDTH, PLAYBUTTON_HEIGHT)];
    [pauseButton setImage:[UIImage imageNamed:@"suspend_button.png"] forState:UIControlStateNormal];
    pauseButton.tag = PAUSE_BUTTON_TAG;
    [pauseButton addTarget:self action:@selector(clickOnButton:) forControlEvents:UIControlEventTouchUpInside];
    
    pauseLabel = [[UILabel alloc] initWithFrame:CGRectMake(PLAYBUTTON_X, PLAYBUTTON_Y+PLAYBUTTON_HEIGHT, PLAYBUTTON_WIDTH, NAVBAR_HEIGHT)];
    [pauseLabel setText:@"暂停"];
    [pauseLabel setTextAlignment:NSTextAlignmentCenter];
    
    
    
    
    timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(TIME_X, TIME_Y, TIME_WIDTH, TIME_HEIGHT)];
    [timeLabel setText:@"00:00:00"];
    [timeLabel setFont:[UIFont systemFontOfSize:32]];
    [timeLabel setTextColor:[UIColor blackColor]];
    
    
    //录音设置
    NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc] init];
    //     设置录音格式  AVFormatIDKey==kAudioFormatLinearPCM
    [recordSetting setValue:[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey];
    //    设置录音采样率(Hz) 如：AVSampleRateKey==8000/44100/96000（影响音频的质量）, 采样率必须要设为11025才能使转化成mp3格式后不会失真
    [recordSetting setValue:[NSNumber numberWithFloat:11025.0] forKey:AVSampleRateKey];
    //     录音通道数1 或2, 要转换成MP3格式必须双通道
    [recordSetting setValue:[NSNumber numberWithInt:2] forKey:AVNumberOfChannelsKey];
    //     线性采样位数 8, 16, 24, 32
    [recordSetting setValue:[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
    //     录音质量
    [recordSetting setValue:[NSNumber numberWithInt:AVAudioQualityHigh] forKey:AVEncoderAudioQualityKey];
   NSString *sandBoxPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSString *songPath= [sandBoxPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.caf",self.path]];

    recordUrl = [NSURL URLWithString:songPath];
    // 初始化
    audioRecorder = [[AVAudioRecorder alloc] initWithURL:recordUrl settings:recordSetting error:nil];
    // 开启音质量检测
    audioRecorder.meteringEnabled = YES;
    audioRecorder.delegate = self;
    
    [SV addSubview:timeLabel];
    [SV addSubview:playButton];
    [SV addSubview:playLabel];
    
    
}
- (void)clickOnButton:(UIButton*)sender {
    audioSession = [AVAudioSession sharedInstance];//得到AVAudioSession单例对象
    switch (sender.tag) {
            
        case NEW_PLAY_BUTTON_TAG:{
            [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
            [audioSession setActive:YES error:nil];
            
            if (mp3FilePath != nil) {
                audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:mp3FilePath error:nil];
            }
            else if (recordUrl != nil){
                audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:recordUrl error:nil];
            }
            
            [audioPlayer prepareToPlay];
            audioPlayer.volume = 1;
            [audioPlayer play];
            
            [playButton removeFromSuperview];
            [playLabel removeFromSuperview];
            [SV addSubview:pauseButton];
            [SV addSubview:pauseLabel];
            
            playDuration = (int)audioPlayer.duration;
            NSLog(@"音频时长为：%i",playDuration);
            playTime = 0;
            [self audioPlayTimeStart];
        }
            break;
        case PAUSE_BUTTON_TAG:{
            [audioPlayer pause];
            [audioSession setActive:NO error:nil];
            
            playButton.tag = PAUSE_PLAY_BUTTON_TAG;
            [pauseButton removeFromSuperview];
            [pauseLabel removeFromSuperview];
            [SV addSubview:playButton];
            [SV addSubview:playLabel];
        }
        default:
            break;
    }
}

- (void)recordTimeStart {
    timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(recordTimeTick) userInfo:nil repeats:YES];
}

- (void)recordTimeTick {
    recordTime += 1;
    //    [progressView setValue:(float)recordTime/30.0 animated:YES];
    if (recordTime == 6000000000000) {
        recordTime = 0;
        [audioRecorder stop];
        [[AVAudioSession sharedInstance] setActive:NO error:nil];
        [timer invalidate];
        [timeLabel setText:@"00:00"];
        [self.view addSubview:playButton];
        [self.view addSubview:playLabel];
        return;
    }
    [self updateAudioRecordTime];
}

- (void)updateAudioRecordTime {
    
    hour = minute / 60.0;
    
    minute = recordTime/60.0;
    second = recordTime-minute*60;
    
    [timeLabel setText:[NSString stringWithFormat:@"%02d:%02d:%02d",hour, minute,second]];
}

- (void)audioPlayTimeStart {
    timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(playTimeTick) userInfo:nil repeats:YES];
}

- (void)playTimeTick {
    if (playDuration == playTime) {
        playTime = 0;
        [audioPlayer stop];
        [[AVAudioSession sharedInstance] setActive:NO error:nil];
        
        [pauseButton removeFromSuperview];
        [pauseLabel removeFromSuperview];
        [SV addSubview:playButton];
        [SV addSubview:playLabel];
        
        playButton.tag = NEW_PLAY_BUTTON_TAG;
        
        [timeLabel setText:@"00:00:00"];
        [timer invalidate];
        //        progressView.value = 0;
        return;
    }
    if (![audioPlayer isPlaying]) {
        return;
    }
    playTime += 1;
    [self updateAudioPlayTime];
}

- (void)updateAudioPlayTime {
    hour = playTime / 60.0 / 60.0;
    minute = playTime / 60.0;
    second = playTime-minute * 60;
    
    [timeLabel setText:[NSString stringWithFormat:@"%02d:%02d:%02d",hour, minute, second]];
}

//AVAudioRecorderDelegate方法
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
    [audioSession setActive:NO error:nil];
    
    playTime = 0;
    
    [pauseButton removeFromSuperview];
    [pauseLabel removeFromSuperview];
    [SV addSubview:playButton];
    [SV addSubview:playLabel];
    
    playButton.tag = NEW_PLAY_BUTTON_TAG;
    
    [timeLabel setText:@"00:00:00"];
    [timer invalidate];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
